<template>
  <div class="dashboard-container">
    <!-- 页面标题栏 -->
    <header class="dashboard-header">
      <h1 class="dashboard-title">智慧实验室系统监控大屏</h1>
      <div class="header-info">
        <el-tag type="info" effect="dark" size="small" class="refresh-interval">
          数据刷新间隔: {{ refreshInterval }}秒
        </el-tag>
        <div class="current-time">{{ currentTime }}</div>
      </div>
    </header>

    <!-- 设备总数和状态概览 -->
    <div class="status-overview">
      <el-card shadow="hover" class="overview-card">
        <div class="overview-item">
          <div class="overview-number">{{ devices.length }}</div>
          <div class="overview-label">项目总数</div>
        </div>
      </el-card>
      <el-card shadow="hover" class="overview-card healthy-card">
        <div class="overview-item">
          <div class="overview-number">{{ healthyDevicesCount }}</div>
          <div class="overview-label">正常项目</div>
        </div>
      </el-card>
      <el-card shadow="hover" class="overview-card warning-card">
        <div class="overview-item">
          <div class="overview-number">{{ warningDevicesCount }}</div>
          <div class="overview-label">异常项目</div>
        </div>
      </el-card>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error-container">
      <el-alert
        title="数据加载失败"
        type="error"
        description="无法获取设备状态信息，请检查网络连接或稍后重试。"
        show-icon
      >
        <template #footer>
          <el-button type="primary" size="small" @click="handleRetry">重试</el-button>
        </template>
      </el-alert>
    </div>

    <!-- 设备监控面板 -->
    <div v-else class="devices-container">
      <monitor-panel
        v-for="device in pagedDevices"
        :key="device.clientId"
        :clientId="device.clientId"
        :systemStatus="device.systemStatus"
        :services="device.services"
        class="monitor-panel-wrapper"
      />
    </div>

    <!-- 分页 -->
    <div v-if="devices.length > 0" class="pagination-container">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :page-size="pageSize"
        :total="devices.length"
        v-model:current-page="currentPage"
        @current-change="handlePageChange"
        class="pagination"
      >
      </el-pagination>
      
      <!-- 自动切换控制 -->
      <div class="auto-switch-control">
        <span class="auto-switch-label">自动切换</span>
        <el-switch
          v-model="autoSwitchEnabled"
          active-text="开启"
          inactive-text="关闭"
          @change="toggleAutoSwitch"
          inline-prompt
          :style="{ '--el-switch-on-color': '#409eff', '--el-switch-off-color': '#909399' }"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
import MonitorPanel from '../components/MonitorPanel.vue';
import { getMockStatusList } from '../api/serviceStatus';

// 响应式数据
const devices = ref([]);
const currentPage = ref(1);
const pageSize = ref(1);  // 每页显示的设备数
const loading = ref(false);
const error = ref(false);
const autoSwitchEnabled = ref(true);
const refreshInterval = ref(8); // 数据刷新间隔（秒）
const currentTime = ref('');

// 定时器
let switchTimer = null;
let refreshTimer = null;
let timeUpdateTimer = null;

// 计算属性
const pagedDevices = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return devices.value.slice(start, end);
});

// 计算正常和异常设备数量
const healthyDevicesCount = computed(() => {
  return devices.value.filter(device => 
    device.services && device.services.every(service => service.healthy)
  ).length;
});

const warningDevicesCount = computed(() => {
  return devices.value.filter(device => 
    device.services && device.services.some(service => !service.healthy)
  ).length;
});

// 方法
async function loadData() {
  loading.value = true;
  error.value = false;
  
  try {
    const res = await getMockStatusList();
    devices.value = res || [];
    
    // 如果当前页没有数据，跳转到第一页
    if (pagedDevices.value.length === 0 && devices.value.length > 0) {
      currentPage.value = 1;
    }
  } catch (err) {
    console.error('获取状态列表失败', err);
    error.value = true;
    devices.value = [];
  } finally {
    loading.value = false;
  }
}

// 自动切换页面
function startAutoSwitch() {
  if (switchTimer) {
    clearInterval(switchTimer);
  }
  
  switchTimer = setInterval(() => {
    if (!autoSwitchEnabled.value) return;
    
    const totalPages = Math.ceil(devices.value.length / pageSize.value);
    if (totalPages > 0) {
      currentPage.value = currentPage.value % totalPages + 1;
    }
  }, 8000); // 每8秒切换一次
}

function stopAutoSwitch() {
  if (switchTimer) {
    clearInterval(switchTimer);
    switchTimer = null;
  }
}

function toggleAutoSwitch() {
  if (autoSwitchEnabled.value) {
    startAutoSwitch();
  } else {
    stopAutoSwitch();
  }
}

function handlePageChange(newPage) {
  currentPage.value = newPage;
  
  // 手动切换页面时，重置自动切换计时器
  if (autoSwitchEnabled.value) {
    startAutoSwitch();
  }
}

function handleRetry() {
  loadData();
}

function updateCurrentTime() {
  currentTime.value = new Date().toLocaleString();
}

// 根据屏幕大小动态调整每页显示的设备数
function adjustPageSize() {
  const screenWidth = window.innerWidth;
  
  // 对于所有设备类型保持每页一个设备，确保在小屏幕上完整显示
  pageSize.value = 1; 
  
  // 调整后确保当前页有效
  const totalPages = Math.max(1, Math.ceil(devices.value.length / pageSize.value));
  if (currentPage.value > totalPages) {
    currentPage.value = totalPages;
  }
}

// 生命周期
onMounted(async () => {
  // 初始化时间显示
  updateCurrentTime();
  timeUpdateTimer = setInterval(updateCurrentTime, 1000);
  
  // 调整页面大小
  adjustPageSize();
  window.addEventListener('resize', adjustPageSize);
  
  // 加载数据
  await loadData();
  
  // 设置数据刷新定时器
  refreshTimer = setInterval(loadData, refreshInterval.value * 1000);
  
  // 启动自动切换
  if (autoSwitchEnabled.value) {
    startAutoSwitch();
  }
});

onUnmounted(() => {
  // 清理所有定时器
  if (switchTimer) clearInterval(switchTimer);
  if (refreshTimer) clearInterval(refreshTimer);
  if (timeUpdateTimer) clearInterval(timeUpdateTimer);
  
  // 移除事件监听
  window.removeEventListener('resize', adjustPageSize);
});
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #001529 0%, #002140 100%);
  color: #fff;
  overflow-x: hidden; /* 防止水平溢出 */
}

/* 页面标题 */
.dashboard-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.dashboard-title {
  font-size: 2.5rem;
  margin: 0 0 15px 0;
  background: linear-gradient(45deg, #409eff, #67c23a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  font-weight: bold;
}

.header-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  font-size: 0.9rem;
}

.refresh-interval {
  background: rgba(64, 158, 255, 0.2);
}

.current-time {
  color: #909399;
}

/* 状态概览 */
.status-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.overview-card {
  background: rgba(10, 31, 61, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 32px rgba(0, 160, 255, 0.2);
}

.overview-item {
  text-align: center;
}

.overview-number {
  font-size: 2.5rem;
  font-weight: bold;
  margin-bottom: 10px;
}

.overview-label {
  color: #909399;
  font-size: 0.9rem;
}

.healthy-card .overview-number {
  color: #67c23a;
}

.warning-card .overview-number {
  color: #f56c6c;
}

/* 加载和错误状态 */
.loading-container,
.error-container {
  background: rgba(10, 31, 61, 0.8);
  border-radius: 8px;
  padding: 30px;
  margin-bottom: 30px;
}

.error-container {
  animation: shake 0.5s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  20%, 60% { transform: translateX(-10px); }
  40%, 80% { transform: translateX(10px); }
}

/* 设备容器 */
.devices-container {
  min-height: 500px;
  margin-bottom: 30px;
}

.monitor-panel-wrapper {
  animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.pagination {
  display: flex;
  justify-content: center;
}

.el-pagination {
  --el-pagination-button-size: 32px;
  --el-pagination-font-size: 14px;
  --el-pagination-border-radius: 6px;
}

.el-pagination .el-pager li {
  margin: 0 5px;
  color: #fff;
}

.el-pagination .el-pager li.active {
  background: #409eff;
  color: #fff;
}

/* 自动切换控制 */
.auto-switch-control {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #909399;
  font-size: 0.9rem;
}

.auto-switch-label {
  white-space: nowrap;
}

/* 响应式设计 - 优化小笔记本显示 */
@media (max-width: 1024px) {
  /* 适用于10英寸小笔记本 */
  .dashboard-container {
    padding: 15px;
  }
  
  .dashboard-title {
    font-size: 2rem;
  }
  
  .overview-number {
    font-size: 2.2rem;
  }
  
  .status-overview {
    gap: 15px;
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }
  
  .dashboard-title {
    font-size: 1.8rem;
  }
  
  .header-info {
    flex-direction: column;
    gap: 10px;
  }
  
  .status-overview {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 20px;
  }
  
  .overview-number {
    font-size: 2rem;
  }
  
  .overview-card {
    padding: 15px 10px;
  }
}

@media (max-width: 600px) {
  /* 适用于更小的笔记本 */
  .dashboard-title {
    font-size: 1.6rem;
  }
  
  .overview-card {
    padding: 12px 8px;
  }
  
  .overview-number {
    font-size: 1.8rem;
  }
  
  .overview-label {
    font-size: 0.8rem;
  }
  
  .header-info {
    font-size: 0.8rem;
  }
  
  .loading-container,
  .error-container {
    padding: 15px;
  }
}

@media (max-width: 480px) {
  .dashboard-title {
    font-size: 1.4rem;
  }
  
  .overview-number {
    font-size: 1.6rem;
  }
  
  .pagination {
    font-size: 0.8rem;
  }
  
  .el-pagination {
    --el-pagination-button-size: 28px;
    --el-pagination-font-size: 12px;
  }
}
</style>
